package com.catemanagement.plugin;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.util.Log;

import com.catemanagement.utils.UpdateManager;

public class UpdatePlugin extends CordovaPlugin {
    private String tag = UpdatePlugin.class.getName();
    private static UpdateManager updateManager;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Application application = this.cordova.getActivity().getApplication();
        if (updateManager == null) {
            updateManager = new UpdateManager(application);
        }
        JSONObject result = new JSONObject();
        if ("checkUpdate".equals(action)) {
            try {
                if (updateManager.isUpdate()) {
                    Log.d(tag, "hasNewVersion:true");
                    result.put("hasNewVersion", true);
                    callbackContext.success(result);

                } else {
                    Log.d(tag, "hasNewVersion:false");
                    result.put("hasNewVersion", false);
                    callbackContext.success(result);
                }
            } catch (Exception e) {
                Log.e(tag, e.getMessage(), e);
                result.put("hasNewVersion", false);
                result.put("msg", "出错:" + e.getMessage());
                callbackContext.error(result);
                return false;
            }

        } else if ("update".equals(action)) {
            updateManager.update();
            result.put("success", true);
            callbackContext.success(result);
        }
        return true;
    }

}
